package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"os/exec"
	"strings"

	"gitee.com/konyshe/gogo"
)

type JSONStruct struct {
	Action    string
	JSONValue interface{}
}

type PcapInfoStruct struct {
	Key        int
	Time       string
	Source     string
	SrcPort    string
	Dstination string
	DstPort    string
	Protocol   string
}

func GetProTshark(filename, r_command string) (pcap_info_list []PcapInfoStruct) {

	// 输入执行的命令
	cmd := exec.Command("tshark", "-r", filename, "-T", "fields", "-e", "frame.time", "-e", "ip.src", "-e", "udp.srcport", "-e", "tcp.srcport", "-e", "ip.dst", "-e", "udp.dstport", "-e", "tcp.dstport", "-e", "frame.protocols")

	// 获取子进程标准输出
	stdout, _ := cmd.StdoutPipe()

	// 执行命令
	cmd.Start()

	// 读取子进程
	reader := bufio.NewReader(stdout)
	for {
		line, err2 := reader.ReadString('\n')
		if err2 != nil || io.EOF == err2 {
			fmt.Printf("Read file error: %s", err2)
			break
		}

		pcap_info_map := strings.Fields(line)

		pcap_info_list = append(pcap_info_list, PcapInfoStruct{
			Key:        len(pcap_info_list) + 1,
			Time:       pcap_info_map[0] + " " + pcap_info_map[1] + " " + pcap_info_map[2] + " " + pcap_info_map[3] + " " + pcap_info_map[4],
			Source:     pcap_info_map[5],
			SrcPort:    pcap_info_map[6],
			Dstination: pcap_info_map[7],
			DstPort:    pcap_info_map[8],
			Protocol:   pcap_info_map[9],
		})

		/*// 转换CMD的编码为GBK
		reader := transform.NewReader(
			bytes.NewReader([]byte(line)),
			simplifiedchinese.GBK.NewDecoder(),
		)
		d, _ := ioutil.ReadAll(reader)

		// 将子进程的内容输出
		print(string(d))*/
	}

	// 模拟CMD暂停
	//bufio.NewReader(os.Stdin).ReadLine()

	return
}

func WSHandle(data []byte, conn *gogo.ImplConnection) ([]byte, error) {
	var recvJSON JSONStruct
	if err := json.Unmarshal(data, &recvJSON); err != nil {
		return nil, err
	}

	switch recvJSON.Action {
	case "get_test":
		{
			recvJSON.JSONValue = GetProTshark("/home/test.pcap", "")
		}

		break
	}

	return json.Marshal(recvJSON)
}
